import React, { ReactChild, Fragment } from 'react'
import { NavBar, Icon, ActionSheet } from 'antd-mobile';
import Router from 'next/router'
// @ts-ignore
import HomeIcon from '../../../icons/home.svg'
// @ts-ignore
import OthersIcon from '../../../icons/others.svg'
// @ts-ignore
import Styles from './index.scss'

// 右边按钮点击类型
type OtherClickType = (index: number) => void

interface PropsInterface {
  // 导航标题
  title: string
  // 是否显示返回按钮
  back: boolean
  // 是否显示home按钮
  home: boolean
  // 其他按钮
  others?: string[]
  // 右侧的其他按钮
  rightIcons: JSX.Element[]
  // 其他按钮点击
  otherClick?: OtherClickType
  // 子元素
  children?: ReactChild,
  // 回退地海， 会将当前界面穷处掉 history
  replace?: string
}

export const iconParameter = {
  className: Styles['right-icon'],
  width: '20px',
  height: '20px',
  fill: '#999'
}

const WNavBar = (props: PropsInterface) => {
  const homeBtnClick = () => {
    Router.push('/')
    Router.replace
  }

  /**
   * 其他按钮点击
   */
  const otherBtnClick = () => {
    const BUTTONS = [...props.others!, '取消'];
    ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      cancelButtonIndex: BUTTONS.length - 1,
      maskClosable: true,
    },
      (buttonIndex: number) => {
        props.otherClick!(buttonIndex)
      });
  }

  /**
   * 返回按钮点击
   */
  const backBtnClick = () => {
    if (props.back) {
      if (props.replace) {
        Router.replace(props.replace)
      } else {
        Router.back()
      }
    }
  }

  // 右边按钮
  const rightContent = []
  if (props.home) {
    rightContent.push(
      <HomeIcon key="home-icon" onClick={homeBtnClick} {...iconParameter} />
    )
  }
  // 添加右侧按钮
  rightContent.push(...props.rightIcons)
  // 其他按钮
  if (props.others && props.others.length > 0) {
    rightContent.push(
      <OthersIcon key="other-icon" onClick={otherBtnClick} {...iconParameter} />
    )
  }

  return (
    <Fragment>
      <NavBar
        className={ Styles['nav-bar'] }
        mode="light"
        icon={props.back ? <Icon type="left" /> : null}
        onLeftClick={ backBtnClick }
        rightContent={rightContent}
      >{props.title}</NavBar>
      <div className={ `${Styles['nav-bar-content']}` }>
        { props.children }
      </div>
    </Fragment>
  )
}

WNavBar.defaultProps = {
  back: true,
  home: true,
  rightIcons: [],
  tabBar: false
};

export default WNavBar